package com.qf.servlet;

import com.qf.entity.*;
import com.qf.service.Card1Service;
import com.qf.service.Card2Service;
import com.qf.service.Credit_CardService;
import com.qf.service.impl.Card1ServiceImpl;
import com.qf.service.impl.Card2ServiceImpl;
import com.qf.service.impl.Credit_CardServiceImpl;
import com.qf.utils.JdbcUtils;
import com.qf.utils.MyUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/cc")
public class Credit_CardServlet extends BaseServlet{

    private Credit_CardService cardService = new Credit_CardServiceImpl();

    private Card1Service card01Service = new Card1ServiceImpl();

    private Card2Service card02Service = new Card2ServiceImpl();

    private void getSessionID(HttpServletRequest req, HttpServletResponse resp){
        Object id = req.getSession().getAttribute("id");
        String s = String.valueOf(id);
        try {
            resp.getWriter().print(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp){
        List<Credit_Card> ccAll = cardService.findCCAll();
        if (ccAll != null){
            try {
                writeHTML(ccAll,resp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp){
        String name = req.getParameter("name");
        String num = req.getParameter("id_num");
        String phone = req.getParameter("phone");
        String uidStr = req.getParameter("uid");

        int uid = Integer.parseInt(uidStr);

        // 拿到登录用户的ID 去比对信息
        User user = cardService.findUIDByCCRegister(name,num,phone);

        if (user != null){

            // 注册，添加信用卡信息到数据库
            String id = MyUtils.getRandomNickname(10);

            Credit_Card card = new Credit_Card(id, 100000, uid, null, "10%",100000,0);
            Boolean flag = cardService.addCC(card);
            System.out.println("card: "+card);
            try {
                if (flag){
                    // 注册成功
                    writeHTML(card,resp);
                }else {
                    // 注册失败
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            // error 注册时,用户信息错误
        }
    }

    private void showCCByID(HttpServletRequest req, HttpServletResponse resp){
        String cid = req.getParameter("cid");
        Credit_Card cc = cardService.findOneByID(cid);
        try {
            if (cc != null){
                writeHTML(cc,resp);
            }else {
                // 没有查到信用卡信息 去注册
                Credit_Card ccNull = new Credit_Card();
                writeHTML(ccNull,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showCCByUID(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        List<Credit_Card> ccs = cardService.findOneByUID(uid);
        try {
            if (ccs.size() > 0){
                writeHTML(ccs,resp);
            }else {
                // 没有查到信用卡信息 去注册
                ccs = null;
                writeHTML(ccs,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void finCard1ByID(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("cid");
        Card1 card = card01Service.findByID(id);
        try {
            writeHTML(card,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void finCard2ByID(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("cid");
        Card2 card = card02Service.findCard2ById(id);
        try {
            writeHTML(card,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
        查询响应充值
     */
    private void findCz(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        String cid = req.getParameter("cid");

        // 查询：信用卡余额
        Credit_Card creditCard = cardService.findOneByID(cid);
        double amount = creditCard.getAmount();
        // 拥有的账户
        List<Card2> card2List = card02Service.findByUid(uid);
        // 响应
        ChongZhi chongZhi = new ChongZhi(amount, card2List);
        try {
            writeHTML(chongZhi,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
        充值业务
     */
    private void cz(HttpServletRequest req, HttpServletResponse resp){
        // 二类卡ID
        String card02ID = req.getParameter("card02ID");
        // 信用卡ID
        String cid = req.getParameter("cid");
        // 充值金额
        String numStr = req.getParameter("num");
        double num = Double.parseDouble(numStr);
        // 用户ID
        String uid = req.getParameter("uid");

        Credit_Card cc = cardService.findOneByID(cid);
        if (cc.getAmount() < num){
            try {
                resp.getWriter().print("6");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 事务
        Connection conn = JdbcUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            Boolean flagC1 = cardService.editByID(num,cid);
            Credit_Card cred_c = cardService.findOneByID(cid);
            double limit = cred_c.getLimit();
            double amount = cred_c.getAmount();
            String interestStr = cred_c.getInterest();
            double v = Double.parseDouble(interestStr.replace("%", ""));
            double interest = v * 0.01;
            boolean flagC2 = false;
            if (amount < limit){
                double lixi = (limit - amount) * interest;
                double repayment = (limit - amount) + lixi;
                flagC2 = cardService.addCCrepayment(repayment,cid);
            }
            Boolean flagC3 = false;
            if (flagC1 && flagC2){
                // 账户加钱
                flagC3 = card02Service.editBalanceByID(num,card02ID);
            }
            if (flagC1 && flagC2 && flagC3){
                conn.commit();
                resp.getWriter().print("Y");
            }else {
                conn.rollback();
                resp.getWriter().print("N");
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }finally {
            JdbcUtils.closeAll(conn,null,null);
        }
    }

    /*
        查询响应提现
     */
    private void findTx(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        String cid = req.getParameter("cid");

        // 查询信用卡余额
        Credit_Card cc = cardService.findOneByID(cid);
        double amount = cc.getAmount();
        // 查询该用户的所有一类银行卡
        List<Card1> c1 = card01Service.findByUid(uid);
        TiXian tiXian = new TiXian(amount, c1);
        try {
            writeHTML(tiXian,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void tx(HttpServletRequest req, HttpServletResponse resp){
        // 信用卡
        String cid = req.getParameter("cid");
        // 一类卡
        String c1 = req.getParameter("c1");
        // 金额
        String numStr = req.getParameter("num");
        double num = Double.parseDouble(numStr);

        Card1 card1 = card01Service.findByID(c1);
        if (card1.getBalance() < num){
            try {
                resp.getWriter().print("6");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 事务
        Connection conn = JdbcUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            // 一类卡扣钱
            boolean flag1 = card01Service.editBalanceByID(num,c1);
            // 信用卡加钱
            boolean flag2 = cardService.jiaqian(num,cid);

            if (flag1 && flag2){
                conn.commit();
                resp.getWriter().print("Y");
            }else {
                conn.rollback();
                resp.getWriter().print("N");
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }finally {
            JdbcUtils.closeAll(conn,null,null);
        }
    }

    private void findHk(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        String cid = req.getParameter("cid");

        Credit_Card cc = cardService.findOneByID(cid);

        double repayment = cc.getRepayment();

        double leastAmount = repayment*0.7;
        BigDecimal b = new BigDecimal(leastAmount);
        leastAmount = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();

        // 查询该用户的所有账户和银行卡
        List<Card1> c1 = card01Service.findByUid(uid);
        List<Card2> c2 = card02Service.findByUid(uid);

        HuanKuan hk = new HuanKuan(repayment, c1, c2,leastAmount);
        try {
            writeHTML(hk,resp);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void hkC1(HttpServletRequest req, HttpServletResponse resp){

        String cid = req.getParameter("ccID");
        String numStr = req.getParameter("num");
        double num = Double.parseDouble(numStr);
        String id = req.getParameter("c1ID");

        Connection conn = JdbcUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            boolean flag1 = cardService.jiaqian(num,cid);
            boolean flag2 = card01Service.jianqian(id, num);
            Credit_Card cc = cardService.findOneByID(cid);
            double repayment = cc.getRepayment() - num;
            boolean flag3 = cardService.addCCrepayment(repayment, cid);
            if (flag1 && flag2 && flag3){
                conn.commit();
                resp.getWriter().print("Y");
            }else {
                conn.rollback();
                resp.getWriter().print("N");
            }
        }catch (Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            JdbcUtils.closeAll(conn,null,null);
        }
    }

    private void hkC2(HttpServletRequest req, HttpServletResponse resp){
        String cid = req.getParameter("ccID");
        String numStr = req.getParameter("num");
        double num = Double.parseDouble(numStr);
        String c2ID = req.getParameter("c2ID");

        Connection conn = JdbcUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            boolean flag1 = card02Service.jianqian(c2ID, num);
            boolean flag2 = cardService.jiaqian(num, cid);
            Credit_Card cc = cardService.findOneByID(cid);
            double repayment = cc.getRepayment() - num;
            boolean flag3= cardService.addCCrepayment(repayment, cid);
            if (flag1 && flag2 && flag3){
                conn.commit();
                resp.getWriter().print("Y");
            }else {
                conn.rollback();
                resp.getWriter().print("N");
            }
        }catch (Exception e){
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException sql) {
                sql.printStackTrace();
            }
        }finally {
            JdbcUtils.closeAll(conn,null,null);
        }
    }
}
